//
//  IDDURLCacheManager.m
//  ComJia
//
//  Created by Aslan on 17/02/2017.
//  Copyright © 2017 ComJia. All rights reserved.
//

#import "IDDURLCacheManager.h"
#import "IDDError+LocalCache.h"

@implementation IDDURLCacheManager

- (instancetype)init
{
    self = [super initWithRoot:@"url"];
    if (self) {
    }
    return self;
}

- (BOOL)canSupportObject:(id)object
{
    return !object || [object isKindOfClass:[NSData class]] || [object isKindOfClass:[NSString class]];
}

- (BOOL)saveObject:(id)object atPath:(NSString *)path error:(IDDError *__autoreleasing *)error
{
    NSData *cacheData = nil;
    if ([object isKindOfClass:[NSData class]]) {
        cacheData = (NSData *)object;
    } else if ([object isKindOfClass:[NSString class]]) {
        NSString *string = (NSString *)object;
        cacheData = [string dataUsingEncoding:NSUTF8StringEncoding];
    }
    NSError *thisError = nil;
    BOOL written = [cacheData writeToFile:path options:NSDataWritingAtomic error:&thisError];
    if (thisError) {
        if (error) {
            *error = cacheErrorWithCode(IDDErrorCacheDomainFilesystemError, thisError);
        }
    }
    return written;
}

- (id)restoreObjectAtPath:(NSString *)path error:(IDDError *__autoreleasing *)error
{
    if (error) {
        *error = nil;
    }
    NSError *thisError = nil;
    NSData *data = [NSData dataWithContentsOfFile:path options:NSDataReadingUncached error:&thisError];
    if (thisError) {
        if ([thisError.domain isEqualToString:NSCocoaErrorDomain] || thisError.code == NSFileReadNoSuchFileError) {
            return nil;
        }
        if (error) {
            *error = cacheErrorWithCode(IDDErrorCacheDomainFilesystemError, thisError);
        }
        return nil;
    }
    return data;
}

@end
